<template>
  <div>
    <transition name="el-fade-in" mode="out-in">
      <div
        v-if="isLoading"
        style="
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 10;
        "
        v-loading="isLoading"
      ></div>
      <div v-else class="root-container">
        <div class="form-container">
          <el-form inline size="small">
            <el-form-item label="起始日期">
              <el-date-picker
                style="width: 150px"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                v-model="formData.begin"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="截止日期">
              <el-date-picker
                style="width: 150px"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                v-model="formData.end"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="main()">
                <el-icon><Search /></el-icon>
                <span>统计</span>
              </el-button>
              <!-- <el-button type="success" @click="exportExcel()">导出</el-button> -->
            </el-form-item>
            <el-form-item v-if="result && result.length > 0">
              <el-divider direction="vertical" />
            </el-form-item>
            <el-form-item v-if="result && result.length > 0" label="过滤">
              <el-radio-group v-model="filterType" @change="handleFilter">
                <el-radio-button value="全部">全部</el-radio-button>
                <el-radio-button value="见习">见习</el-radio-button>
                <el-radio-button value="放单">放单</el-radio-button>
                <el-radio-button value="教员">教员</el-radio-button>
                <el-radio-button value="带班">OMA/SUP</el-radio-button>
              </el-radio-group>
              <span style="min-width: 8px"></span>
              <el-input
                v-model="filterText"
                placeholder="姓名或工牌号"
                @change="handleFilter"
                style="width: 120px"
              ></el-input>
              <span style="min-width: 8px"></span>
            </el-form-item>
            <el-form-item v-if="result && result.length > 0">
              <el-divider direction="vertical" />
            </el-form-item>
            <el-form-item v-if="result && result.length > 0">
              <el-button type="primary" @click="handleExport">
                <span>导出为Excel</span>
                <el-icon><Download /></el-icon>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table-container" :style="{ height: tableHeight + 'px' }">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2
                v-if="result && result.length > 0"
                :columns="columnsFiltered"
                :data="resultFiltered"
                :width="width"
                :height="height"
                fixed
              />
            </template>
          </el-auto-resizer>
        </div>
        <!-- <pre>{{ columnsFiltered }}</pre> -->
        <!-- <pre>{{ JSON.stringify(info, null, 2) }}</pre> -->
        <!-- <pre>{{ JSON.stringify(result, null, 2) }}</pre> -->
      </div>
    </transition>
    <AlertView v-if="showAlert" />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import dayjs from "dayjs";
import useCommonStore from "@/store/common.js";
import hourSummary from "./hourSummary.js";
import requestData from "./requestData.js";
import generateColumns from "./generateColumns.js";
import AlertView from "@/components/Alert/index.vue";
import useSeatStore from "@/store/seat.js";
import exportExcel from "./exportExcel.js";

const seatStore = useSeatStore();
const commonStore = useCommonStore();
const showAlert = computed(() => !seatStore.isServiceAvailable);

const formData = ref({
  begin: dayjs().subtract(1, "month").format("YYYY-MM") + "-20",
  end: dayjs().format("YYYY-MM") + "-19",
  orgid: 13,
});

const getRange = () => {
  let start = dayjs(formData.value.begin).format("YYYY-MM-DD") + " 00:00:00";
  let end = dayjs(formData.value.end).format("YYYY-MM-DD") + " 23:59:59";
  return { start, end };
};

const columns = computed(() => generateColumns());

const tableHeight = computed(() => commonStore.clientHeight - 150);

const result = ref(null);
const info = ref(null);
const isLoading = ref(false);

const main = () => {
  isLoading.value = true;
  let t0 = dayjs().valueOf();
  let t1 = 0;
  let t2 = 0;
  let c0 = 0;
  let c1 = 0;
  requestData(getRange())
    .then((data) => {
      t1 = dayjs().valueOf();
      c0 = data.length;
      result.value = hourSummary(data);
      t2 = dayjs().valueOf();
      c1 = Object.keys(result.value).length;
      filterType.value = "全部";
      filterText.value = "";
      addQualifyRemark();
      handleFilter();
      info.value = {
        version: dayjs().format("DD日HH时mm分"),
        requestTime: t1 - t0,
        computeTime: t2 - t1,
        totalTime: t2 - t0,
        sourceCount: c0,
        resultCount: c1,
      };
      isLoading.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

const filterType = ref("全部");
const resultFiltered = ref([]);
const columnsFiltered = ref([]);
const filterText = ref("");

const addQualifyRemark = () => {
  for (let i = 0; i < result.value.length; i++) {
    let cell = result.value[i];
    if (cell["带班席"] > 0) {
      cell["资质"] = "带班";
    } else if (cell["带培"] > 0) {
      cell["资质"] = "教员";
    } else if (cell["见习"] == cell["合计"]) {
      cell["资质"] = "见习";
    } else {
      cell["资质"] = "放单";
    }
  }
  // console.log("addQualifyRemark", result.value);
};

const handleFilter = () => {
  //
  resultFiltered.value =
    result.value == null
      ? []
      : filterType.value == "见习"
      ? result.value.filter((cell) => cell["见习"] > 0)
      : filterType.value == "教员"
      ? result.value.filter((cell) => cell["带培"] > 0)
      : filterType.value == "放单"
      ? result.value.filter((cell) => cell["带培"] == 0 && cell["见习"] == 0)
      : filterType.value == "带班"
      ? result.value.filter(
          (cell) => cell["带班席"] > 0 || cell["军民航席"] > 0
        )
      : result.value;
  //
  if (filterText.value != "") {
    resultFiltered.value = resultFiltered.value.filter(
      (cell) =>
        cell["姓名"].includes(filterText.value) ||
        (cell["工牌号"] + "").includes(filterText.value)
    );
  }
  //
  columnsFiltered.value =
    result.value == null
      ? []
      : filterType.value == "见习"
      ? columns.value.filter((cell) =>
          [
            "姓名",
            "工牌号",
            "资质",
            "合计",
            "管制席见习",
            "协调席见习",
            "带班席见习",
            "军民航席见习",
            "见习",
          ].includes(cell.key)
        )
      : filterType.value == "教员"
      ? columns.value.filter((cell) =>
          [
            "姓名",
            "工牌号",
            "资质",
            "合计",
            "管制席",
            "协调席",
            "管制席带培",
            "协调席带培",
            "管制席独立",
            "协调席独立",
            "带培",
            "独立",
          ].includes(cell.key)
        )
      : filterType.value == "带班"
      ? columns.value.filter((cell) =>
          [
            "姓名",
            "工牌号",
            "资质",
            "合计",
            "管制席",
            "协调席",
            "管制席带培",
            "协调席带培",
            "管制席独立",
            "协调席独立",
            "军民航席",
            "军民航席带培",
            "军民航席独立",
            "带班席",
            "带班席带培",
            "带班席独立",
            "带培",
            "独立",
          ].includes(cell.key)
        )
      : filterType.value == "放单"
      ? columns.value.filter((cell) =>
          ["姓名", "工牌号", "资质", "合计", "管制席", "协调席"].includes(
            cell.key
          )
        )
      : columns.value;
  //
  let maxWidth =
    commonStore.clientWidth -
    (commonStore.showSidebar ? commonStore.sidebarWidth : 0) -
    9;
  // console.log("maxWidth", maxWidth);
  let columnWidth = Math.max(
    parseInt(maxWidth / columnsFiltered.value.length),
    60
  );
  // columnsFiltered.value.forEach((col, i, arr) => (arr[i].width = columnWidth));
  columnsFiltered.value.forEach((col) => (col.width = columnWidth));

  // console.log("handleFilter_columnsFiltered", columnsFiltered.value);
  // console.log("handleFilter_resultFiltered", resultFiltered.value);
};
const handleExport = () => {
  exportExcel({
    columns: columnsFiltered.value,
    rows: resultFiltered.value,
    startDate: dayjs(formData.value.begin).format("YYYY-MM-DD"),
    endDate: dayjs(formData.value.end).format("YYYY-MM-DD"),
    version: info.value.version + "_" + filterType.value,
  });
};
</script>

<style scoped>
pre {
  font-family: Consolas, "Courier New", Courier, monospace;
}

.root-container {
  padding: 24px 3px 0px 3px;
}

.form-container {
  padding: 0 24px;
}

.table-container {
  width: 100%;
  height: 100%;
}
</style>
